/**
 * 
 */
package com.gf.pf.dao;

import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.DaoSupport;
import static org.springframework.util.Assert.notNull;

/**
 * @description MyBatisDao
 * @date Mar 7, 2015
 */
public class MyBatisDao extends DaoSupport {

	private SqlSession sqlSession;

	private SqlSessionFactory sqlSessionFactory;

	private boolean externalSqlSession;

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
		if (!this.externalSqlSession) {
			this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
		}
	}

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSession = sqlSessionTemplate;
		this.externalSqlSession = true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.dao.support.DaoSupport#checkDaoConfig()
	 */
	@Override
	protected void checkDaoConfig() throws IllegalArgumentException {
		notNull(this.sqlSession,"Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
	}

	/**
	 * 
	 * @description 保存
	 * @return int
	 */
	public int insert(String key, Object object) {
		return sqlSession.insert(key, object);
	}

	/**
	 * 
	 * @description 删除
	 * @return int
	 */
	public int delete(String key, Object object) {
		return sqlSession.delete(key, object);
	}

	/**
	 * 
	 * @description 修改
	 * @return int
	 */
	public int update(String key, Object object) {
		return sqlSession.update(key, object);
	}

	/**
	 * 
	 * @description 获得对象
	 * @return Object
	 */
	public Object get(String key, Object object) {
		return sqlSession.selectOne(key, object);
	}

	/**
	 * 
	 * @description 总记录数
	 * @return int
	 */
	public int count(String key, Object object) {
		return (Integer) sqlSession.selectOne(key, object);
	}

	/**
	 * 
	 * @description 对象列表
	 * @return List<?>
	 */
	public List<?> getList(String key) {
		return sqlSession.selectList(key);
	}

	/**
	 * 
	 * @description 带参数的对象列表
	 * @return List<?>
	 */
	public List<?> getList(String key, Object object) {
		return sqlSession.selectList(key, object);
	}

	/**
	 * 
	 * @description 批量插入
	 * @return boolean
	 */
	public boolean batchInsert(String key, List<?> objList) {
		SqlSession session = this.sqlSessionFactory.openSession(ExecutorType.BATCH, false);
		int i = 0;
		for (; i < objList.size(); i++) {
			session.insert(key, objList.get(i));
		}
		session.flushStatements();
		if (i == objList.size()) {
			return true;
		}
		return false;
	}

}
